package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findMaxScoreRecommendUser(Long toUserId) {
        // 1.构建查询条件
        Query query = new Query(
                Criteria.where("toUserId").is(toUserId) // 条件
        ).with(Sort.by(Sort.Order.desc("score"))) // 排序
                .skip(0).limit(1); // 取第一条

        // 2.查询推荐用户
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        // 3.返回结果
        return recommendUser;
    }

    // 查询推荐用户分页列表
    @Override
    public PageBeanVo findRecommendUserByPage(Long toUserId, Integer pageNum, Integer pageSize) {
        // 1.构建查询条件
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query(
                Criteria.where("toUserId").is(toUserId) // 条件
        ).with(Sort.by(Sort.Order.desc("score")))// 排序
                .skip(index + 1).limit(pageSize); // 分页（排除第一条）

        // 2.查询recommendUser集合
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        // 3.查询总记录数
        long count = mongoTemplate.count(query, RecommendUser.class);

        // 4.返回并封装分页对象
        return new PageBeanVo(pageNum, pageSize, count, recommendUserList);
    }

    /**
     * @param toUserId 当前用户
     * @param userId   推荐用户
     */
    @Override
    public RecommendUser findRecommendUserByCondition(Long toUserId, Long userId) {
        // 1.构建查询条件
        Query query = new Query(
                Criteria.where("toUserId").is(toUserId)
                        .and("userId").is(userId)
        );
        // 2.查询推荐用户对象
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        // 3.返回推荐用户对象
        return recommendUser;
    }

    @Override
    public void remove(Long toUserId, Long userId) {
        // 1.构建删除条件
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        // 2.删除
        mongoTemplate.remove(query, RecommendUser.class);
    }
}
